//
//  BDPostLayout.m
//  BadBoy
//
//  Created by wen on 2017/8/30.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPostLayout.h"
//#import <NSAttributedString+YYText.h>
#import "BDTextLinePositionModifier.h"
#import "BDPostHelper.h"

@implementation BDPostLayout

- (instancetype)initWithPost:(BDPostModel *)post {
    if (!post || !post.user) return nil;
    if (self = [super init]) {
        _post = post;
        [self layout];
    }
    return self;
}

- (void)layout {
    [self _layout];
    [self _calculateHeight];
}

- (void)calculateHeight{
    [self _calculateHeight];
}

- (void)_layout {
    _marginTop = kBDCellTopMargin;
    _profileHeight = 0;
    _textHeight = 0;
    _retweetHeight = 0;
    _retweetTextHeight = 0;
    _retweetPicHeight = 0;
    _retweetCardHeight = 0;
    _picHeight = 0;
    _cardHeight = 0;
    _toolbarHeight = kBDCellToolbarHeight;
    _marginBottom = kBDCellToolbarBottomMargin;
    
    [self _layoutProfile];
    [self _layoutText];
    [self _layoutRetweet];
    if (_retweetHeight == 0) {
        [self _layoutPics];
        [self _layoutCard];
    }
    [self _layoutToolbar];
}

- (void)_calculateHeight{
    // 计算高度
    _height = 0;
    _height += _marginTop;
    _height += _profileHeight;
    if (_isOpen == YES) {
        _height += _textHeight;
    }else{
        _height += _minTextHeight;
        _height += kBDCellPadding;
    }
    if (_needOpenButton == YES) {
        _height += _openButtonHeight;
        _height += kBDCellPadding;
    }
    
    if (_retweetHeight > 0) {
        _height += kBDCellPadding;
        _height += _retweetHeight;
    } else {
        if (_picHeight > 0) {
            _height += kBDCellPadding;
            _height += _picHeight;
        }
        if (_cardHeight > 0) {
            _height += kBDCellPadding;
            _height += _cardHeight;
        }
    }
    _height += _toolbarHeight;
    _height += _marginBottom;
    
    _detailHeight = 0;
    _detailHeight += _marginTop;
    _detailHeight += _profileHeight;
    _detailHeight += _textHeight;
    if (_retweetHeight > 0) {
        _detailHeight += kBDCellPadding;
        _detailHeight += _retweetHeight;
    }else {
        if (_picHeight > 0) {
            _detailHeight += kBDCellPadding;
            _detailHeight += _picHeight;
        }
        //卡片这里要区分购买了还是没有购买
        if (_cardHeight > 0 && (_isDetail == NO || ([_post isPurchase] == NO && _isDetail == YES))) {
            _detailHeight += kBDCellPadding;
            _detailHeight += _cardHeight;
        }
    }
    _detailHeight += _marginBottom;
}

/// 文本
- (void)_layoutText {
    _textHeight = 0;
    _textLayout = nil;
    
    NSMutableAttributedString *text = [self _textWithPost:_post
                                                isRetweet:NO
                                                 fontSize:kBDCellTextFontSize
                                                textColor:kBDCellTextNormalColor];
    if (text.length == 0) return;
    
    BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
    modifier.font = [UIFont fontWithName:@"Heiti SC" size:kBDCellTextFontSize];
    modifier.paddingTop = kBDCellPaddingText;
    modifier.paddingBottom = 0;
    
    YYTextContainer *container = [YYTextContainer new];
    container.size = CGSizeMake(kBDCellContentWidth, MAXFLOAT);
    container.linePositionModifier = modifier;
    
    _textLayout = [YYTextLayout layoutWithContainer:container text:text];
    if (!_textLayout) return;
    
    _textHeight = [modifier heightForLineCount:_textLayout.rowCount];
    _minTextHeight = [modifier heightForLineCount:6];
    if (_minTextHeight < _textHeight) {
        _needOpenButton = YES;
        _isOpen = NO;
        _openButtonHeight= kBDCellOpenButtonHeight;
    }else{
        _needOpenButton = NO;
        _isOpen = YES;
    }
    _textHeight += kBDCellPaddingText;
}

///用户信息
- (void)_layoutProfile {
    [self _layoutName];
    [self _layoutSource];
    _profileHeight = kBDCellProfileHeight;
}

- (void)_layoutName {
    BDUserModel *user = _post.user;
    NSString *nameStr = user.nickname;
    if (nameStr.length == 0) {
        _nameTextLayout = nil;
        return;
    }
    
    NSMutableAttributedString *nameText = [[NSMutableAttributedString alloc] initWithString:nameStr];
    
    // VIP
    if (user.vip_level > 0) {
        UIImage *yelllowVImage = [BDPostHelper imageNamed:@"user_vip"];
        NSAttributedString *vipText = [BDPostHelper attachmentWithFontSize:kBDCellNameFontSize image:yelllowVImage shrink:NO];
        [nameText appendString:@" "];
        [nameText appendAttributedString:vipText];
    }
    
    nameText.font = [UIFont systemFontOfSize:kBDCellNameFontSize];
    nameText.color = user.vip_level > 0 ? kBDCellNameOrangeColor : kBDCellNameNormalColor;
    nameText.lineBreakMode = NSLineBreakByCharWrapping;
    
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kBDCellNameWidth, 9999)];
    container.maximumNumberOfRows = 1;
    _nameTextLayout = [YYTextLayout layoutWithContainer:container text:nameText];
}

- (void)_layoutSource {
    NSMutableAttributedString *sourceText = [NSMutableAttributedString new];
    NSString *createTime = [BDPostHelper stringWithTimelineDate:[NSDate dateWithTimeIntervalSince1970:_post.posted_at]];
    
    // 时间
    if (createTime.length) {
        NSMutableAttributedString *timeText = [[NSMutableAttributedString alloc] initWithString:createTime];
        [timeText appendString:@"  "];
        timeText.font = [UIFont systemFontOfSize:kBDCellSourceFontSize];
        timeText.color = kBDCellTimeNormalColor;
        [sourceText appendAttributedString:timeText];
    }
    
    if (sourceText.length == 0) {
        _sourceTextLayout = nil;
    } else {
        YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kBDCellNameWidth, 9999)];
        container.maximumNumberOfRows = 1;
        _sourceTextLayout = [YYTextLayout layoutWithContainer:container text:sourceText];
    }
}

///图片
- (void)_layoutPics {
    [self _layoutPicsWithPost:_post isRetweet:NO];
}

- (void)_layoutRetweetPics {
    [self _layoutPicsWithPost:_post.repost isRetweet:YES];
}

- (void)_layoutPicsWithPost:(BDPostModel *)post isRetweet:(BOOL)isRetweet {
    if (isRetweet) {
        _retweetPicSize = CGSizeZero;
        _retweetPicHeight = 0;
    } else {
        _picSize = CGSizeZero;
        _picHeight = 0;
    }
    if (post.images.count == 0) return;
    
    CGSize picSize = CGSizeZero;
    CGFloat picHeight = 0;
    
    CGFloat len1_3 = (kBDCellContentWidth + kBDCellPaddingPic) / 3 - kBDCellPaddingPic;
    len1_3 = CGFloatPixelRound(len1_3);
    switch (post.images.count) {
        case 1: {
            picSize = CGSizeMake(200, 150);
            picHeight = 150;
        } break;
        case 2: case 3: {
            picSize = CGSizeMake(len1_3, len1_3);
            picHeight = len1_3;
        } break;
        case 4: case 5: case 6: {
            picSize = CGSizeMake(len1_3, len1_3);
            picHeight = len1_3 * 2 + kBDCellPaddingPic;
        } break;
        default: { // 7, 8, 9
            picSize = CGSizeMake(len1_3, len1_3);
            picHeight = len1_3 * 3 + kBDCellPaddingPic * 2;
        } break;
    }
    
    if (isRetweet) {
        _retweetPicSize = picSize;
        _retweetPicHeight = picHeight;
    } else {
        _picSize = picSize;
        _picHeight = picHeight;
    }
}

///转发
- (void)_layoutRetweet {
    _retweetHeight = 0;
    [self _layoutRetweetedText];
    [self _layoutRetweetPics];
    [self _layoutRetweetCard];
    
    _retweetHeight = _retweetTextHeight;
    if (_retweetPicHeight > 0) {
        _retweetHeight += _retweetPicHeight;
        _retweetHeight += kBDCellPadding;
    }
    if (_retweetCardHeight > 0) {
        _retweetHeight += _retweetCardHeight;
        _retweetHeight += kBDCellPadding;
    }
}

//设置卡片
- (void)_layoutCard {
    [self _layoutCardWithPost:_post isRetweet:NO];
}

- (void)_layoutRetweetCard {
    [self _layoutCardWithPost:_post isRetweet:YES];
}

- (void)_layoutCardWithPost:(BDPostModel *)post isRetweet:(BOOL)isRetweet {
    BDPostModel *currentPost = nil;
    if (isRetweet) {
        _retweetCardType = BDPostCardTypeNone;
        _retweetCardHeight = 0;
        _retweetCardTextLayout = nil;
        _retweetCardTextRect = CGRectZero;
        currentPost = post.repost;
    } else {
        _cardType = BDPostCardTypeNone;
        _cardHeight = 0;
        _cardTextLayout = nil;
        _cardTextRect = CGRectZero;
        currentPost = post;
    }
    BOOL haveShopInfo = currentPost.price != 0 || [currentPost.shop isNotEmpty] || [currentPost.address isNotEmpty] || [currentPost.contact isNotEmpty] || [currentPost.consumption isNotEmpty];
    if (haveShopInfo == NO) return;
    
    BDPostCardType cardType = BDPostCardTypeNone;
    CGFloat cardHeight = 0;
    YYTextLayout *cardTextLayout = nil;
    CGRect textRect = CGRectZero;
    
    /*
     badge: 25,25 左上角 (42)
     image: 70,70 方形
     100, 70 矩形
     btn:  60,70
     
     lineheight 20
     padding 10
     */
    textRect.size.height = 70;
    textRect.origin.x = 80;
    textRect.origin.x += 10; //padding
    textRect.size.width = kBDCellContentWidth - textRect.origin.x;
    textRect.size.width -= 20; //padding
    
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    if ([post isPurchase] == YES) {
        //购买过了
        if (currentPost.shop.length) {
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:ASLocalizedString(@"商家店名：%@"), currentPost.shop]];
            title.font = [UIFont systemFontOfSize:kBDCellCardTitleFontSize];
            title.color = kBDCellNameNormalColor;
            [text appendAttributedString:title];
        }
        if (currentPost.address.length) {
            if (text.length) [text appendString:@"\n"];
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:ASLocalizedString(@"商家地址：%@"), currentPost.address]];
            title.font = [UIFont systemFontOfSize:kBDCellCardTitleFontSize];
            title.color = kBDCellNameNormalColor;
            [text appendAttributedString:title];
        }
        if (currentPost.contact.length) {
            if (text.length) [text appendString:@"\n"];
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:ASLocalizedString(@"联系方式：%@"), currentPost.contact]];
            title.font = [UIFont systemFontOfSize:kBDCellCardTitleFontSize];
            title.color = kBDCellNameNormalColor;
            [text appendAttributedString:title];
        }
    }else{
        BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
        BDUserModel *currentUser = [BDUserModel getCurrentUser];
        
        if (isControl == YES || currentUser.is_auth == NO){
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:ASLocalizedString(@"主题内容已加密，点击查看解锁方式")];
            title.font = [UIFont systemFontOfSize:kBDCellCardTitleFontSize];
            title.color = kBDCellNameNormalColor;
            [text appendAttributedString:title];
        }else{
            NSString *labelStr = [NSString stringWithFormat:ASLocalizedString(@"查看商家联系方式需向作者支付 %.2f元 才能浏览 点击查看"), currentPost.price];
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:labelStr];
            title.font = [UIFont systemFontOfSize:kBDCellCardTitleFontSize];
            title.color = kBDCellNameNormalColor;
            NSRange range = [labelStr rangeOfString:[NSString stringWithFormat:ASLocalizedString(@" %.2f元 "), currentPost.price]];
            //标记文字点击事件[UIColor colorWithHexString:@"#ff9300"]
            [title setTextHighlightRange:range color:[UIColor orangeColor] backgroundColor:nil tapAction:nil];
            
            NSRange range2 = [labelStr rangeOfString:ASLocalizedString(@"点击查看")];
            //标记文字点击事件
            [title setTextHighlightRange:range2 color:KBDColorBlue backgroundColor:nil tapAction:nil];
        }
    }
    
    if (text.length) {
        text.maximumLineHeight = 20;
        text.minimumLineHeight = 20;
        text.lineBreakMode = NSLineBreakByTruncatingTail;
        
        YYTextContainer *container = [YYTextContainer containerWithSize:textRect.size];
        container.maximumNumberOfRows = 3;
        cardTextLayout = [YYTextLayout layoutWithContainer:container text:text];
    }
    
    if (cardTextLayout) {
        cardType = currentPost.price == 0 ? BDPostCardTypeFree : BDPostCardTypeCharge;
        cardHeight = 70;
    }
    
    if (isRetweet) {
        _retweetCardType = cardType;
        _retweetCardHeight = cardHeight;
        _retweetCardTextLayout = cardTextLayout;
        _retweetCardTextRect = textRect;
    } else {
        _cardType = cardType;
        _cardHeight = cardHeight;
        _cardTextLayout = cardTextLayout;
        _cardTextRect = textRect;
    }
}

//工具条
- (void)_layoutToolbar {
    UIFont *font = [UIFont systemFontOfSize:kBDCellToolbarFontSize];
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenWidth, kBDCellToolbarHeight)];
    container.maximumNumberOfRows = 1;
    
    NSMutableAttributedString *likeText = [[NSMutableAttributedString alloc] initWithString:_post.praiseCount <= 0 ? ASLocalizedString(@"赞"): [BDPostHelper shortedNumberDesc:_post.praiseCount]];
    likeText.font = font;
    likeText.color = _post.praiseCount ? kBDCellToolbarTitleHighlightColor : kBDCellToolbarTitleColor;
    _toolbarLikeTextLayout = [YYTextLayout layoutWithContainer:container text:likeText];
    _toolbarLikeTextWidth = CGFloatPixelRound(_toolbarLikeTextLayout.textBoundingRect.size.width);
    
    NSMutableAttributedString *repostText = [[NSMutableAttributedString alloc] initWithString:_post.repostCount <= 0 ? ASLocalizedString(@"转发"): [BDPostHelper shortedNumberDesc:_post.repostCount]];
    repostText.font = font;
    repostText.color = kBDCellToolbarTitleColor;
    _toolbarRepostTextLayout = [YYTextLayout layoutWithContainer:container text:repostText];
    _toolbarRepostTextWidth = CGFloatPixelRound(_toolbarRepostTextLayout.textBoundingRect.size.width);
    
    NSMutableAttributedString *commentText = [[NSMutableAttributedString alloc] initWithString:_post.commentCount <= 0 ? ASLocalizedString(@"评论"): [BDPostHelper shortedNumberDesc:_post.commentCount]];
    commentText.font = font;
    commentText.color = kBDCellToolbarTitleColor;
    _toolbarCommentTextLayout = [YYTextLayout layoutWithContainer:container text:commentText];
    _toolbarCommentTextWidth = CGFloatPixelRound(_toolbarCommentTextLayout.textBoundingRect.size.width);
    
    NSMutableAttributedString *sharedText = [[NSMutableAttributedString alloc] initWithString:_post.sharedCount <= 0 ? ASLocalizedString(@"分享"): [BDPostHelper shortedNumberDesc:_post.sharedCount]];
    sharedText.font = font;
    sharedText.color = kBDCellToolbarTitleColor;
    _toolbarSharedTextLayout = [YYTextLayout layoutWithContainer:container text:sharedText];
    _toolbarSharedTextWidth = CGFloatPixelRound(_toolbarSharedTextLayout.textBoundingRect.size.width);
}

///对转发文本的处理
- (void)_layoutRetweetedText {
    _retweetHeight = 0;
    _retweetTextLayout = nil;
    NSMutableAttributedString *text = [self _textWithPost:_post.repost
                                                isRetweet:YES
                                                 fontSize:kBDCellTextFontRetweetSize
                                                textColor:kBDCellTextSubTitleColor];
    if (text.length == 0) return;
    
    BDTextLinePositionModifier *modifier = [BDTextLinePositionModifier new];
    modifier.font = [UIFont fontWithName:@"Heiti SC" size:kBDCellTextFontRetweetSize];
    modifier.paddingTop = kBDCellPaddingText;
    modifier.paddingBottom = kBDCellPaddingText;
    
    YYTextContainer *container = [YYTextContainer new];
    container.size = CGSizeMake(kBDCellContentWidth, HUGE);
    container.linePositionModifier = modifier;
    
    _retweetTextLayout = [YYTextLayout layoutWithContainer:container text:text];
    if (!_retweetTextLayout) return;
    
    _retweetTextHeight = [modifier heightForLineCount:_retweetTextLayout.lines.count];
}

///对文本的处理
- (NSMutableAttributedString *)_textWithPost:(BDPostModel *)post
                                   isRetweet:(BOOL)isRetweet
                                    fontSize:(CGFloat)fontSize
                                   textColor:(UIColor *)textColor {
    if (!post) return nil;
    
    NSMutableString *string = post.post.mutableCopy;
    if (string.length == 0) return nil;
    if (isRetweet) {
        NSString *name = post.user.nickname;
//        if (name.length == 0) {
//            name = status.user.screenName;
//        }
        if (name) {
            NSString *insert = [NSString stringWithFormat:@"@%@:",name];
            [string insertString:insert atIndex:0];
        }
    }
    // 字体
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    // 高亮状态的背景
    YYTextBorder *highlightBorder = [YYTextBorder new];
    highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
    highlightBorder.cornerRadius = 3;
    highlightBorder.fillColor = kBDCellTextHighlightBackgroundColor;
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
    text.font = font;
    text.color = textColor;
    
//    // 根据 urlStruct 中每个 URL.shortURL 来匹配文本，将其替换为图标+友好描述
//    for (WBURL *wburl in status.urlStruct) {
//        if (wburl.shortURL.length == 0) continue;
//        if (wburl.urlTitle.length == 0) continue;
//        NSString *urlTitle = wburl.urlTitle;
//        if (urlTitle.length > 27) {
//            urlTitle = [[urlTitle substringToIndex:27] stringByAppendingString:YYTextTruncationToken];
//        }
//        NSRange searchRange = NSMakeRange(0, text.string.length);
//        do {
//            NSRange range = [text.string rangeOfString:wburl.shortURL options:kNilOptions range:searchRange];
//            if (range.location == NSNotFound) break;
//            
//            if (range.location + range.length == text.length) {
//                if (status.pageInfo.pageID && wburl.pageID &&
//                    [wburl.pageID isEqualToString:status.pageInfo.pageID]) {
//                    if ((!isRetweet && !status.retweetedStatus) || isRetweet) {
//                        if (status.pics.count == 0) {
//                            [text replaceCharactersInRange:range withString:@""];
//                            break; // cut the tail, show with card
//                        }
//                    }
//                }
//            }
//            
//            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
//                
//                // 替换的内容
//                NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:urlTitle];
//                if (wburl.urlTypePic.length) {
//                    // 链接头部有个图片附件 (要从网络获取)
//                    NSURL *picURL = [WBStatusHelper defaultURLForImageURL:wburl.urlTypePic];
//                    UIImage *image = [[YYImageCache sharedCache] getImageForKey:picURL.absoluteString];
//                    NSAttributedString *pic = (image && !wburl.pics.count) ? [self _attachmentWithFontSize:fontSize image:image shrink:YES] : [self _attachmentWithFontSize:fontSize imageURL:wburl.urlTypePic shrink:YES];
//                    [replace insertAttributedString:pic atIndex:0];
//                }
//                replace.font = font;
//                replace.color = kWBCellTextHighlightColor;
//                
//                // 高亮状态
//                YYTextHighlight *highlight = [YYTextHighlight new];
//                [highlight setBackgroundBorder:highlightBorder];
//                // 数据信息，用于稍后用户点击
//                highlight.userInfo = @{kWBLinkURLName : wburl};
//                [replace setTextHighlight:highlight range:NSMakeRange(0, replace.length)];
//                
//                // 添加被替换的原始字符串，用于复制
//                YYTextBackedString *backed = [YYTextBackedString stringWithString:[text.string substringWithRange:range]];
//                [replace setTextBackedString:backed range:NSMakeRange(0, replace.length)];
//                
//                // 替换
//                [text replaceCharactersInRange:range withAttributedString:replace];
//                
//                searchRange.location = searchRange.location + (replace.length ? replace.length : 1);
//                if (searchRange.location + 1 >= text.length) break;
//                searchRange.length = text.length - searchRange.location;
//            } else {
//                searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
//                if (searchRange.location + 1>= text.length) break;
//                searchRange.length = text.length - searchRange.location;
//            }
//        } while (1);
//    }
//    
//    // 根据 topicStruct 中每个 Topic.topicTitle 来匹配文本，标记为话题
//    for (WBTopic *topic in status.topicStruct) {
//        if (topic.topicTitle.length == 0) continue;
//        NSString *topicTitle = [NSString stringWithFormat:@"#%@#",topic.topicTitle];
//        NSRange searchRange = NSMakeRange(0, text.string.length);
//        do {
//            NSRange range = [text.string rangeOfString:topicTitle options:kNilOptions range:searchRange];
//            if (range.location == NSNotFound) break;
//            
//            if ([text attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
//                [text setColor:kWBCellTextHighlightColor range:range];
//                
//                // 高亮状态
//                YYTextHighlight *highlight = [YYTextHighlight new];
//                [highlight setBackgroundBorder:highlightBorder];
//                // 数据信息，用于稍后用户点击
//                highlight.userInfo = @{kWBLinkTopicName : topic};
//                [text setTextHighlight:highlight range:range];
//            }
//            searchRange.location = searchRange.location + (searchRange.length ? searchRange.length : 1);
//            if (searchRange.location + 1>= text.length) break;
//            searchRange.length = text.length - searchRange.location;
//        } while (1);
//    }
    
    // 匹配 @用户名
    NSArray *atResults = [[BDPostHelper regexAt] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    for (NSTextCheckingResult *at in atResults) {
        if (at.range.location == NSNotFound && at.range.length <= 1) continue;
        if ([text attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil) {
            [text setColor:kBDCellTextHighlightColor range:at.range];
            
            // 高亮状态
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBackgroundBorder:highlightBorder];
            // 数据信息，用于稍后用户点击
            highlight.userInfo = @{kBDLinkAtName : [text.string substringWithRange:NSMakeRange(at.range.location + 1, at.range.length - 1)]};
            [text setTextHighlight:highlight range:at.range];
        }
    }
    
    // 匹配 [表情]
    NSArray<NSTextCheckingResult *> *emoticonResults = [[BDPostHelper regexEmoticon] matchesInString:text.string options:kNilOptions range:text.rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([text attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([text attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [text.string substringWithRange:range];
        NSString *imageName = [BDPostHelper emoticonDic][emoString][@"gif"];
        
        UIImage *image = [BDPostHelper imageNamed:imageName];
        if (!image) continue;
        
        NSAttributedString *emoText = [NSAttributedString attachmentStringWithEmojiImage:image fontSize:fontSize];
        [text replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
    return text;
}


@end
